<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/layui/css/layui.css" media="all">
    <!-- 注意：如果你直接复制所有代码到本地，上述css路径需要改成你本地的 -->
</head>
<body>

<form class="layui-form" lay-filter="search" id="search" style="padding-top: 10px">
    <div class="layui-form-item">
        <!--        layui-inline,外层行内-->
        <div class="layui-inline">
            <label class="layui-form-label">分类名</label>
            <div class="layui-input-inline">
                <input type="text" name="cateName" placeholder="请输入分类名" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <button class="layui-btn" lay-submit lay-filter="formDemo">查询</button>
            <button type="reset" id="searchReset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>

<!--添加表单-->
<form class="layui-form" action="" style="display: none" id="addCategory" lay-filter="addBusinessFormFilter">
    <!-- 这里设置一个隐藏域，用来存放我们的图片的地址 -->
    <input type="hidden" id="addImagePath" name="addImagePath" value="">

    <div class="layui-form-item">
        <label class="layui-form-label" style="width: 100px">商品分类名称</label>
        <div class="layui-input-inline">
            <input type="text" id="addCateName" name="name" required lay-verify="required" placeholder="请输入商品分类名称"
                   autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item layui-form-text">
        <label class="layui-form-label" style="width: 100px">上传按钮</label>
        <div class="layui-input-block">
            <button type="button" class="layui-btn" id="test2">
                <i class="layui-icon">&#xe67c;</i>上传图片
            </button>
        </div>
    </div>
    <div class="layui-form-item layui-form-text">
        <label class="layui-form-label" style="width: 100px">图片预览</label>
        <div class="layui-input-block">
            <img id="addImage" style="width: 100px;height: 100px">
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="addSubmit">立即提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>
<!--编辑表单-->
<form class="layui-form" action="" style="display: none" id="editCategory" lay-filter="editBusinessFormFilter">
    <!-- 这里设置一个隐藏域，用来存放我们的图片的地址 -->
    <input type="hidden" id="imagePath" name="imagePath" value="">
    <input type="hidden" id="id" name="id" value="">
    <div class="layui-form-item">
        <label class="layui-form-label" style="width: 100px">商品分类名称</label>
        <div class="layui-input-inline">
            <input type="text" id="cateName" name="name" required lay-verify="required" placeholder="请输入商品分类名称"
                   autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item layui-form-text">
        <label class="layui-form-label" style="width: 100px">上传按钮</label>
        <div class="layui-input-block">
            <button type="button" class="layui-btn" id="test1">
                <i class="layui-icon">&#xe67c;</i>上传图片
            </button>
        </div>
    </div>
    <div class="layui-form-item layui-form-text">
        <label class="layui-form-label" style="width: 100px">图片预览</label>
        <div class="layui-input-block">
            <img id="image" style="width: 100px;height: 100px">
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="editSubmit">立即提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>

<table class="layui-hide" id="test" lay-filter="demo"></table>


<script src="/layui/layui.js" charset="utf-8"></script>
<!-- 注意：如果你直接复制所有代码到本地，上述 JS 路径需要改成你本地的 -->
<script type="text/html" id="imgtmp">
    <img src="{{d.cateIcon}}" style="height: 20px;height: 20px"/>
</script>
<script>
    layui.use(['table', 'jquery', 'form', 'upload'], function () {
        var table = layui.table;
        var $ = layui.$,
            form = layui.form,
            upload = layui.upload;
        var table_category = table.render({
            elem: '#test'
            , toolbar: '#toolbarDemo'
            , url: '/category/getPage'
            , cols: [
                [
                    {type: 'checkbox'}
                    , {field: 'id', width: 80, title: 'ID', sort: true}
                    , {field: 'cateIcon', width: 140, title: '分类图标', templet: "#imgtmp", align: "center"}
                    , {field: 'cateName', width: 100, title: '分类名', align: "center"}
                    , {field: 'right', title: '操作', toolbar: '#barDemo', width: '9%', align: 'center'}

                ]
            ]
            , page: true
            , limit: 10
            , limits: [5, 10, 15, 20, 25, 30]
        });
//查询
        form.on('submit(formDemo)', function (data) {
            table.reload('test', {
                where: {
                    cateName: data.field.cateName
                }
            });
            return false;
        });
        //监听表格复选框选择
        table.on('checkbox(demo)', function (obj) {
            console.log(obj.tr)
        });
        //监听工具条
        table.on('tool(demo)', function (obj) {
            var data = obj.data;
            // if (obj.event === 'detail') {
            //     layer.msg('ID：' + data.id + ' 的查看操作');
            // } else
            if (obj.event === 'del') {
                layer.confirm('真的删除行么', function (index) {
                    console.log(data.id)
                    var data_t = {
                        "id": data.id,
                    };
                    $.post("/category/deleteCategory",
                        {"id": data.id},
                        function (res) {
                            if (res.code == 0) {
                                layer.msg("删除成功");
                                layer.closeAll();
                                table.reload('test', {
                                        url: '/category/getPage',
                                        page: {
                                            curr: 1 //重新从第 1 页开始
                                        },
                                    }
                                );

                            }
                        });
                    // $.ajax({
                    //         url: "/category/deleteCategory",
                    //         method: "post",
                    //         contentType:'application/json;charset=UTF-8',
                    //         data:JSON.stringify(data_t) ,
                    //         success: function (res){
                    //             if (res.code ==0){
                    //                 layer.msg("删除成功");
                    //                 layer.closeAll();
                    //                 table_category.reload();
                    //
                    //             }
                    //         }
                    // })

                    layer.close(index);
                });
            } else if (obj.event === 'edit') {


                layer.open({
                    type: 1,
                    title: false,
                    area: ['500px', '400px'], //宽高
                    // closeBtn: 0, //不显示关闭按钮
                    // scrollbar: false, //禁止浏览器出现滚动条
                    // resize: false, //禁止拉伸
                    // move: false, //禁止拖拽
                    // shade: 0.8, //遮罩
                    // shadeClose: true, //点击遮罩关闭当前页面
                    content: $("#editCategory"), //这里content是一个Url
                    success: function (layero, index) {//弹出层打开后的回调函数,数据回显
                        //updateNumber为弹出层id,eaccidentNumber为数据表格的field属性
                        $('#id').val(data.id);
                        $('#cateName').val(data.cateName);
                        $('#imagePath').val(data.cateIcon);
                        $("#image").attr("src", data.cateIcon);
                    },
                })
            }
        });
        <!--toolbar添加删除功能-->
        table.on('toolbar(demo)', function (obj) {
            var check = table.checkStatus(obj.config.id)
                , data = check.data;
            switch (obj.event) {
                case 'add':
                    $("#addCategory")[0].reset();
                    $("#addImage").attr("src", " ");
                    layer.open({

                        title: '添加商品类别',
                        type: 1,
                        area: ['550px', '400px'],
                        content: $("#addCategory")
                    });
                    break;
                case 'dels':
                    if (data.length === 0) {
                        layer.msg('请选择一行');
                    } else {
                        var ids = [];
                        for (var i = 0; i < data.length; i++) {
                            ids[i] = data[i].id;
                        }
                        console.log(ids);
                        layer.confirm('真的删除行么', function (index) {
                            $.ajax({
                                url: '/category/batchDeleteCategory',//路径
                                type: 'post',//post/sget
                                data: {ids: ids},//传给后台的参数
                                dataType: 'json',//相应的数据类型,
                                success: function (result) {
                                    //成功响应函数
                                    if (result.code == 0) {
                                        layer.closeAll();
                                        table.reload('test', {
                                                url: '/category/getPage',
                                                page: {
                                                    curr: 1 //重新从第 1 页开始
                                                },
                                            }
                                        );
                                        layer.msg(result.msg, {icon: 6});
                                    } else {
                                        layer.msg(result.msg, {icon: 5});
                                    }
                                }
                            });
                        });
                    }
                    break;
            }
        });

        <!--图片上传-->

        //执行实例
        let uploadEdit = upload.render({
            elem: '#test1' //绑定元素
            , url: '/category/image' //上传接口
            , done: function (res) {
                if (res.code == 0) {
                    layer.msg("上传成功");
                    //获得图片的路径
                    let src = res.data.src;
                    //将图片进行回显
                    $("#image").attr("src", src);
                    //将图片的地址赋值给 form的隐藏域
                    $("#imagePath").attr("value", src);
                }
            }
            , error: function () {
                //请求异常回调
            }
        });
        //添加表单的上传图片
        let uploadAdd = upload.render({
            elem: '#test2' //绑定元素
            , url: '/category/image' //上传接口
            , done: function (res) {
                console.log(res.data)
                if (res.code == 0) {
                    layer.msg("上传成功");
                    //获得图片的路径
                    let src = res.data.src;
                    //将图片进行回显
                    $("#addImage").attr("src", src);
                    //将图片的地址赋值给 form的隐藏域
                    $("#addImagePath").attr("value", src);
                }
            }
            , error: function () {
                //请求异常回调
            }
        });
        //监听编辑表单的提交
        form.on('submit(editSubmit)', function (data) {
            data = data.field;
            var data_t = {
                "id": data.id,
                "cateIcon": data.imagePath,
                "cateName": data.name,
            }
            console.log(data)
            console.log(data_t)
            $.ajax({
                url: "/category/updateCategory",
                method: "post",
                contentType: 'application/json;charset=UTF-8',
                data: JSON.stringify(data_t),
                success: function (res) {
                    if (res.code == 0) {
                        layer.msg("修改成功");
                        layer.closeAll();
                        table_category.reload();

                    }
                }
            })
            return false;
        });
        //监听添加表单的提交
        form.on('submit(addSubmit)', function (data) {
            data = data.field;
            console.log(data);
            var data_t = {
                "cateIcon": data.addImagePath,
                "cateName": data.name,
            }
            console.log(data_t.cateIcon)
            console.log(data_t.cateName)
            // $.post("/category/addCategory",{
            //     headers:{
            //         'content-type':'application/json;charset=UTF-8',
            //     }
            // },
            //     {
            //         "cateIcon": data.addImagePath,
            //         "cateName": data.name,
            //     },
            //     function (res) {
            //         if (res.code == 0) {
            //             layer.msg("添加成功");
            //             layer.closeAll();
            //             table_category.reload();
            //
            //         }
            //     },
            //     "json"
            // );
            $.ajax({
                url: "/category/addCategory",
                method: "post",
                contentType: 'application/json;charset=UTF-8',
                data: JSON.stringify(data_t),
                success: function (res) {
                    if (res.code == 0) {
                        layer.msg("添加成功");
                        layer.closeAll();
                        table_category.reload();

                    }
                }
            })
            return false;
        });

    });
</script>

<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<script type="text/html" id="toolbarDemo">
    <a class="layui-btn layui-btn-xs" lay-event="add">添加</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="dels">删除</a>
</script>


</body>
</html>